﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Kaiser.FilterProviders.FilterCriterion;

namespace Kaiser.FilterProviders
{
    public class FilterRegistryItem
    {
        private readonly List<IFilterCriteria> _filterCriteria;

        public Filter Filter { get; private set; }

        public FilterRegistryItem(Filter filter)
            : this(null, filter){ }

        public FilterRegistryItem(IEnumerable<IFilterCriteria> filterCriteria, Filter filter)
        {
            if (filter == null)
                throw new ArgumentNullException("filter");

            if (filterCriteria == null)
                filterCriteria = Enumerable.Empty<IFilterCriteria>();


            object filterInstance = filter.Instance;

            if (filterInstance==null||!(filterInstance is IActionFilter
                ||filterInstance is IAuthorizationFilter
                ||filterInstance is IExceptionFilter
                ||filterInstance is IResultFilter))
                throw new ArgumentOutOfRangeException("filterInstance");

            this._filterCriteria = filterCriteria.ToList();
            Filter = filter;
        }
       
        public bool Match(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            return _filterCriteria.Aggregate(true, (prev, f) => prev ? f.Match(controllerContext, actionDescriptor) : prev);
        }
    }
}
